import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:my_app/base/foundation/jd_colors.dart';
import 'package:my_app/base/utils/jd_log.dart';
import 'package:my_app/modules/pages/home/home_page.dart';
import 'package:my_app/modules/pages/login/login_tool.dart';
import 'package:my_app/modules/tools/iap/ios_pay.dart';

import '../../base/widget/basic/base_lifecycle_page.dart';
import '../config/jd_enum.dart';

class TabNavigator extends StatefulWidget {
  const TabNavigator({super.key});

  @override
  State<TabNavigator> createState() => _TabNavigatorState();
}

class _TabNavigatorState extends State<TabNavigator> {
  final PageController _controller = PageController(
    initialPage: 0,
  );

  int _currentIndex = 0;

  final selectTabGlobalKey = {
    TabBarType.home.value: GlobalKey(),
    TabBarType.second.value: GlobalKey(),
    // TDTabBarType.consult.value: GlobalKey(),
    // TDTabBarType.mine.value: GlobalKey(),
  };

  @override
  void initState() {
    super.initState();
    if (defaultTargetPlatform == TargetPlatform.iOS) {
      InAppPurchaseStoreKitPlatform.registerPlatform();
    }
    Future.delayed(const Duration(seconds: 1), () {
      delayAction();
    });

    Future.delayed(Duration.zero, () {
      GlobalKey? lastTabGlobalKey = selectTabGlobalKey[_currentIndex];
      jdLog('lastTabGlobalKey----> $lastTabGlobalKey');
      final lastState = lastTabGlobalKey?.currentState as BaseLifecycleState?;
      if (lastState != null) {
        print("1lastState.didTabPush--------->");
        lastState.didTabPush();
      }
    });
  }

  delayAction() async {
    if (LoginTool.isLogin()) {
      if (defaultTargetPlatform == TargetPlatform.iOS) {
        //内购监听
        await IOSPayment.instance.init();
        IOSPayment.instance.startSubscription();
        // 查询没完成订单 进入支付页面 调用一下
        // TDIOSPayment.instance.checkUnfinishedPayment(() => null);
      }
    }
  }

  changeIndex(int oldIndex, int nowIndex) {
    if (nowIndex == oldIndex) {
      return;
    }
    // WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    //   final currentSelectTab = nowIndex;
    //   final currentTabGlobalKey = selectTabGlobalKey[currentSelectTab];
    //   final lastState =
    //       selectTabGlobalKey[oldIndex]?.currentState as BaseLifecycleState?;
    //
    //   if (lastState != null) {
    //     lastState.didTabPop();
    //     print("tab 离开---------> $oldIndex ");
    //   }
    //   final currentState =
    //       currentTabGlobalKey?.currentState as BaseLifecycleState?;
    //   if (currentState != null) {
    //     currentState.didTabPush();
    //     print("tab 显示---------> $nowIndex");
    //   }
    // });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        controller: _controller,
        onPageChanged: (index) {
          changeIndex(_currentIndex, index);
          setState(() {
            _currentIndex = index;
          });
        },
        physics: const NeverScrollableScrollPhysics(),
        children: <Widget>[
          HomePage(
            key: selectTabGlobalKey[TabBarType.home.value],
          ),
          HomePage(
            key: selectTabGlobalKey[TabBarType.second.value],
          ),
          // HomePage(key: selectTabGlobalKey[TDTabBarType.consult.value]),
          // HomePage(key: selectTabGlobalKey[TDTabBarType.mine.value])
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          _controller.jumpToPage(index);
          // if (index == TDTabBarType.consult.value) {
          //   RefreshNotifier.consultNumNotifier.refresh(setData: 0);
          // }
        },
        backgroundColor: const Color(0xffffffff),
        type: BottomNavigationBarType.fixed,
        selectedItemColor: JDColors.c222222,
        unselectedItemColor: JDColors.c222222,
        selectedFontSize: 10,
        unselectedFontSize: 10,
        items: [
          _navigationBarItem(
            'bar_home.png',
            'bar_home_selected.png',
            '首页',
          ),
          _navigationBarItem('bar_report.png', 'bar_report_selected.png', '报告'),
          // _navigationBarItem(
          //     'bar_question.png', 'bar_question_selected.png', '问答'),
          // //  RefreshNotifier.consultNumNotifier
          // _navigationBarItem(
          //     'bar_consult.png', 'bar_consult_selected.png', '咨询'),
          // _navigationBarItem('bar_mine.png', 'bar_mine_selected.png', '我的'),
        ],
      ),
    );
  }

  _navigationBarItem(String normalImage, String selectedImage, String itemName,
      [ValueNotifier<int>? valueNotifier]) {
    if (valueNotifier != null) {
      Widget pointWidget = Positioned(
        child: Center(
          child: Transform.translate(
            offset: const Offset(12, -8),
            child: ValueListenableBuilder(
              valueListenable: valueNotifier,
              builder: (BuildContext context, int value, Widget? child) =>
                  Visibility(
                visible: value > 0,
                child: UnconstrainedBox(
                  child: Container(
                    constraints:
                        const BoxConstraints(minWidth: 16, minHeight: 16),
                    padding: const EdgeInsets.only(top: 1, left: 3, right: 3),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: const Color(0xFFFECC32),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(
                      '${valueNotifier.value}',
                      style: const TextStyle(
                          color: Colors.black,
                          fontSize: 12,
                          fontWeight: FontWeight.w600),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      );
      return BottomNavigationBarItem(
        icon: Icon(Icons.home),

        // Stack(
        //   children: [
        //     Center(
        //       child: JDAssetImage(
        //         '$fTabBar/$normalImage',
        //         width: 24,
        //         height: 24,
        //       ),
        //     ),
        //     pointWidget
        //   ],
        // ),
        activeIcon: Stack(
          children: [Icon(Icons.local_fire_department), pointWidget],
        ),
        label: itemName,
      );
    } else {
      return BottomNavigationBarItem(
        icon: Icon(Icons.favorite),
        activeIcon: Icon(Icons.favorite),
        label: itemName,
      );
    }
  }
}
